package org.papillion39.sechelper.auth;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.login.LoginException;
import com.sun.appserv.security.AppservPasswordLoginModule;
import com.sun.enterprise.security.auth.realm.BadRealmException;

/**
 *
 * @author Jonathan Paz <jonathan.paz@ottr.com>
 */
public class JDBCSaltedDigestLoginModule extends AppservPasswordLoginModule {
    private static final Logger LOG = Logger.getLogger(JDBCSaltedDigestLoginModule.class.getName());

    @Override
    protected void authenticateUser() throws LoginException {
        if (!(_currentRealm instanceof JDBCSaltedDigestRealm)) {
            LoginException e = new LoginException(String.format("Unknown realm: %s",_currentRealm.getClass().getName()));
            LOG.throwing("org.papillion39.sechelper.modules.authentication.JDBCSaltedDigestLoginModule", "authenticateUser", e);
            throw e;
        }
        if (_username == null || _username.isEmpty()) {
            LoginException e = new LoginException("Cannot authenticate a null user");
            LOG.throwing("org.papillion39.sechelper.modules.authentication.JDBCSaltedDigestLoginModule", "authenticateUser", e);
            throw e;
        }
        JDBCSaltedDigestRealm realm = (JDBCSaltedDigestRealm) _currentRealm;
        LOG.finer("Identified the realm as a JDBC Salted Digest Realm");
        try {
            LOG.log(Level.FINER, "Authenticating user {0}", _username);
            String[] groups = realm.authenticate(_username, _passwd);
            if (groups == null) {
                LoginException e = new LoginException(String.format("Could not authenticate user: %s",_username));
                LOG.throwing("org.papillion39.sechelper.modules.authentication.JDBCSaltedDigestLoginModule", "authenticateUser", e);
                throw e;
            }
            LOG.log(Level.FINER, "Authenticated user {0}",_username);
            commitUserAuthentication(groups);
            LOG.log(Level.FINER, "Committed user authentication");
        } catch (BadRealmException e) {
            LoginException ee = new LoginException("The realm was improperly configured");
            ee.initCause(e);
            LOG.throwing("org.papillion39.sechelper.modules.authentication.JDBCSaltedDigestLoginModule", "authenticateUser", ee);
            throw ee;
        }
    }

}
